<?php

/**
 * ApiRpc.class.php 
 * 
 *
 * @author     late.xiao@qq.com
 */
namespace Base\Lib;

class ApiRpc {
    const ERR_CODE = 500;
    protected static $_interface = array();
    public $app;

    public function __construct($app)
    {

        $this->app = $app;
    }

    static public function get($app)
    {

        if (! (self::$_interface [$app] instanceof self))
        {
            self::$_interface [$app] = new self($app);
        }
        
        return self::$_interface[$app];
    }
    // 调用API
    public function rpcCall($api_name, $params = array())
    {
        // 检验接口是否定义
        $api_info = null;
        if (! $api_name || ! $this->_checkApiExists($api_name, $api_info))
        {throw new \Exception($api_name . ' is not valid', self::ERR_CODE);}
        
        // 验证类和方法是否存在
        $class_name = null;
        $method = null;
        $this->_checkApiValid($api_name, $api_info);
        list($class_name, $method) = $api_info;
        
        // 验证参数是否合法
        $this->_checkParamsValid($class_name, $params);
        // 开始处理接口请求
        $result = call_user_func_array(array($class_name, $method), array($params));
        
        return $result;
    }

    // 检验接口是否定义
    protected function _checkApiExists($api_name, &$api_info)
    {

        if (! $api_name)
        {return false;}
        
        $api_list = C('api');
        if (array_key_exists($api_name, $api_list))
        {
            $api_info = $api_list [$api_name];
            
            return true;
        }
        
        return false;
    }

    // 验证类和方法是否存在
    protected function _checkApiValid($api_name, &$api_info)
    {
        $api_arr = explode('@', $api_info ['uses']);
        if (! $api_arr)
        {throw new \Exception($api_name . ' definition error', self::ERR_CODE);}
        
        list($app, $class_name, $method) = $api_arr;
        $class_name = "\\" . $app . "\\Api\\" . $class_name;
        if (! class_exists($class_name))
        {throw new \Exception($class_name . ' does not exist', self::ERR_CODE);}
        
        if (! method_exists($class_name, $method))
        {throw new \Exception($method . ' does not exist in the ' . $class_name, self::ERR_CODE);}
        
        $api_info = array();
        $api_info[] = $class_name;
        $api_info[] = $method;
        
        return true;
    }

    // 验证参数是否合法
    protected function _checkParamsValid($class_name, &$params)
    {
        return true;
    }

}
 